from django.core.cache import cache
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from app.models import Post, User
from celery_tasks.sms.tasks import ccp_send_sms_code



class PostAPIView(APIView):
    def post(self, request):
        title=request.data.get('title')
        content=request.data.get('content')
        userid=request.data.get('user')
        user=User.objects.get(id = int(userid))
        Post.objects.create(title=title, content=content,user=user)
        ccp_send_sms_code.delay()
        if all ([title, content, userid]):
            return JsonResponse({'code': 200, 'msg': '添加成功'})
        else:
            return JsonResponse({'code': 400, 'msg': '添加失败'})

    def get(self, request):

        if cache.get('post_list'):
            return Response({
                'code': 200,
                'msg': 'redis成功',
                'data': cache.get('post_list')
            })
        else:

            return Response({ 'code': 200,'msg': 'redis失败' })

        sql1 = "SELECT post.*, user.* FROM post JOIN user ON post.user = user.user_id ORDER BY post.time DESC;"  # 编写一条原生sql语句
        row =Post.objects.raw(sql1)

        # with connection.cursor() as cursor:
        #     cursor.execute(sql1)  # 执行sql
        #     row = cursor.fetchall()  # 获取所有结果集
        # return JsonResponse({'code':200,'msg':'成功','data':row})

        page_size = 4
        page_number = request.GET.get('page')

        paginator = Paginator(row, page_size)

        try:
            page_objects = paginator.page(page_number)
        except PageNotAnInteger:
            # 如果页码不是一个整数，则返回第一页
            page_objects = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，则返回最后一页
            page_objects = paginator.page(paginator.num_pages)
        list=[]
        list_post= []
        userid = request.data.get('user')
        user = User.objects.get(id=int(userid))


        for i in page_objects:
            print(i.name)
            list_post.append({
                'title':i.title,
            }),
        list.append({'userid':user,
                     'post':list_post
                     })

        if cache.set('post_list', list_post, 900):
            print('数据库查询成功')
            return Response({
                'code': 200,
                'msg': '成功',
                'data': list})
        else:
            return Response({
                'code': 400,
                'msg': '失败',
            })




